package com.quanyan.club.pullclub.service.impl;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.quanyan.api.APIRequest;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.AssetsPayReceive;
import com.quanyan.api.enums.AssetsType;
import com.quanyan.assets.request.ReqUserAccumulateModify;
import com.quanyan.assets.service.UserAssetsService;
import com.quanyan.club.constants.ClubConstants;
import com.quanyan.club.entity.db.*;
import com.quanyan.club.entity.vo.resp.RespClubActivity;
import com.quanyan.club.mapper.*;
import com.quanyan.club.pullclub.entity.req.ChannelSellDo;
import com.quanyan.club.pullclub.service.PullClubService;
import com.quanyan.club.pullclub.service.PullClubSupportService;
import com.quanyan.club.pullclub.utils.DES;
import com.quanyan.club.service.CppService;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.exception.BizException;
import com.quanyan.common.utils.BeanCopierUtils;
import com.quanyan.common.utils.CommonUtils;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.common.utils.Limit;
import com.quanyan.user.response.RespUserInfoBase;
import com.quanyan.user.response.RespUserInfoDetail;
import com.quanyan.user.serviceFacade.UserServiceFacade;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.method.P;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by yue.yuan on 2017/2/13.
 */
@Service("pullClubSupportService")
public class PullClubSupportServiceImpl implements PullClubSupportService {

    private static Logger logger = Logger.getLogger(PullClubSupportServiceImpl.class);
    @Autowired
    private ClubActivityMapper clubActivityMapper;
    @Autowired
    private TbClubMapper tbClubMapper;
    @Autowired
    private TbSignUserMapper tbSignUserMapper;
    @Autowired
    private TbChannelUserMapper tbChannelUserMapper;
    @Autowired
    private TbClubIntegralRuleMapper tbClubIntegralRuleMapper;
    @Autowired
    private TbChannelClubEggMapper tbChannelClubEggMapper;
    @Autowired
    private TbChannelStreamMapper tbChannelStreamMapper;
    @Autowired
    private TbChannelMapper tbChannelMapper;
    @Autowired
    private TbChannelSellMapper tbChannelSellMapper;
    @Autowired
    private UserServiceFacade userServiceFacade;
    @Autowired
    private TbActivityMapper tbActivityMapper;
    @Autowired
    private UserAssetsService userAssetsService;
    @Autowired
    private CppService cppService;


    /**
     * 拉新成功
     * @param respClubActivity
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean pullUserSuccess(TbChannelUser tbChannelUser,
                                   RespClubActivity respClubActivity, TbClub club,
                                   List<Integer> signUsers) {
        int activityId = respClubActivity.getActivityId();
        //校验的最后一步，校验报名人数
        Date clubCreateTime = club.getCreateTime();
        List<Integer> effectiveUsers = new ArrayList<Integer>();
        for(Integer signUser : signUsers) {
            if(isNewSignUser(signUser, activityId, clubCreateTime)) {
                effectiveUsers.add(signUser);
            }
        }
        if(effectiveUsers.size() < getSignCountsSetting(ClubConstants.RULE_SETTING_PULL_GRADE)) {
            logger.warn("拉新奖励：报名人数小于限制人数---FAIL：当前人数："
                    + effectiveUsers.size());
            return false;
        }
        int effectiveCounts = effectiveUsers.size();
        //获得奖励的次数
        int count = tbChannelUser.getClubActivityCount();
        Map<String, Object> map = getPointBy(ClubConstants.PULL_GAINS_AMOUNT_SETTING);
        List<Integer> grades= (List<Integer>) map.get(ClubConstants.RULE_SETTING_PULL_GRADE);
        int limitCount = 3;
        if(CollectionUtils.isNotEmpty(grades)) {
            limitCount = grades.get(0) > 0 ? grades.get(0) : limitCount;
        }
        if(count >= limitCount) {
            logger.warn("拉新奖励：活动奖励次数超过最大奖励次数----FAIL：当前次数："
                    + count + ",最大次数:" + limitCount);
            return false;
        }
        logger.warn("拉新奖励所有校验通过，进入发派奖励逻辑----PASS");
        //增加次数
        tbChannelUser.setClubActivityCount(count + 1);
        if(tbChannelUser.getClubId() != club.getId()) {
            logger.warn("第一个创建的俱乐部和完成奖励俱乐部不同，对记录进行更新,老ID:"
                    + tbChannelUser.getClubId() + ",完成俱乐部ID：" + club.getId());
            TbChannelUser updateChannelUser = new TbChannelUser();
            updateChannelUser.setId(tbChannelUser.getId());
            updateChannelUser.setClubId(club.getId());
            tbChannelUserMapper.updateByPrimaryKeySelective(updateChannelUser);
            tbChannelUser.setClubId(club.getId());
        }
        int pullEgg = getPointEggs(effectiveCounts,
                ClubConstants.PULL_NEW_CLUB_EGGS_SETTING);

        Map<Integer, Long> eggMap =
                new HashMap<Integer, Long>();
        String msg = null;
        String newClubMsg = null;
        int oldClubEgg = 0;
        if(tbChannelUser.getType() == 2) {
            //老带新俱乐部奖励鸟蛋
            oldClubEgg = getPointEggs(effectiveCounts,
                    ClubConstants.PULL_OLD_CLUB_EGGS_SETTING);
            tbChannelUser.setOldClubAwardEgg(tbChannelUser.getOldClubAwardEgg() + oldClubEgg);
            eggMap.put(tbChannelUser.getOldClubUid(), (long)oldClubEgg);
            insertPullClubEgg(tbChannelUser.getOldClubUid(), club.getId(), activityId,
                    respClubActivity.getLowestPrice(), effectiveCounts,
                    oldClubEgg, ClubConstants.PULLL_OLD_CLUB_EGG_TYPE);
            eggMap.put(tbChannelUser.getUid(), (long)pullEgg);
            insertPullClubEgg(tbChannelUser.getUid(), club.getId(), activityId,
                    respClubActivity.getLowestPrice(), effectiveCounts, pullEgg,
                    ClubConstants.PULLL_NEW_CLUB_EGG_TYPE);
            msg = "获得老带新奖励鸟蛋" + oldClubEgg;
            newClubMsg = "获得新俱乐部奖励鸟蛋" + pullEgg;

        } else {
            //渠道经销商返利
            //根据次数判断获得奖励多少
            int money = 0;
            if(tbChannelUser.getClubActivityCount() == 1 ||
                    tbChannelUser.getClubActivityCount() == 2) {
                money = 20;
            } else if (tbChannelUser.getClubActivityCount() == 3) {
                money = 30;
            }
            channelIncome(tbChannelUser, money);
            //渠道奖励鸟蛋
            eggMap.put(tbChannelUser.getUid(), (long)pullEgg);
            insertPullClubEgg(tbChannelUser.getUid(), club.getId(), activityId,
                    respClubActivity.getLowestPrice(), effectiveCounts, pullEgg,
                    ClubConstants.PULL_CHANNEL_CLUB_EGG_TYPE);
        }
        if(tbChannelUser.getClubActivityCount() == 1) {
            tbChannelUser.setDrawCount(1);
        }
        tbChannelUser.setClubAwardEgg(tbChannelUser.getClubAwardEgg() + pullEgg);
        updatePullStatus(tbChannelUser, ClubConstants.PULL_STATUS_SUCCESS);
        APIResponse apiResponse = getEgg(eggMap);
        if(null == apiResponse || !apiResponse.isRet()) {
            throw new BizException("鸟蛋发放失败：" + apiResponse.getErrmsg());
        }
        try {
            //发送老带新消息通知
            if(tbChannelUser.getType() == 2) {
                APIResponse<RespUserInfoBase> response =
                        userServiceFacade.queryUserInfo(tbChannelUser.getOldClubUid());
                String logoUrl = null;
                if(response == null || !response.isRet()){
                    logoUrl = club.getLogoUrl();
                } else {
                    logoUrl = response.getData().getIcon();
                }
                if (tbChannelUser.getClubActivityCount() == 1) {
                    cppService.pullClubSuccess2DrawAward(logoUrl,
                            "你已成功拉新俱乐部，获得抽奖机会，点击消息进入抽奖页面",
                            Arrays.asList(tbChannelUser.getOldClubUid()));
                }
                if(oldClubEgg > 0) {
                    cppService.pushClubCommonMsg(
                            logoUrl, msg,
                            Arrays.asList(tbChannelUser.getOldClubUid()));
                }
                if(pullEgg > 0) {
                    APIResponse<RespUserInfoBase> responseNew =
                            userServiceFacade.queryUserInfo(tbChannelUser.getUid());
                    String newLogoUrl = null;
                    if(responseNew == null || !responseNew.isRet()){
                    } else {
                        newLogoUrl = responseNew.getData().getIcon();
                    }
                    cppService.pushClubCommonMsg(
                            newLogoUrl, newClubMsg,
                            Arrays.asList(tbChannelUser.getUid()));
                }

            }
        } catch (Exception e) {
            logger.warn("发送老带新消息通知失败：" + e.getMessage());
        }

        return true;
    }

    /**
     * 更新拉新状态
     * @param tbChannelUser
     * @param targetStatus
     * @return
     */
    public boolean updatePullStatus(TbChannelUser tbChannelUser, byte targetStatus) {
        if(null != tbChannelUser) {
            tbChannelUser.setCreateTime(null);
            tbChannelUser.setUpdateTime(null);
            tbChannelUser.setStatus(targetStatus);
            return tbChannelUserMapper.updateByPrimaryKeySelective(tbChannelUser) == 1;
        }
        return false;
    }

    /**
     * 是否满足拉新条件
     * @param uid 拉新用户UID
     * @param tbClub
     * @param activityId
     * @param targetStatus
     * @return
     */
    public TbChannelUser isPullUser(int uid, TbClub tbClub, Integer activityId,
                                    Byte targetStatus, Date activityCreateTime) {
        Integer clubId = (null == tbClub ? null : tbClub.getId());
        //注册
        TbChannelUserExample tbChannelUserExample = new TbChannelUserExample();
        TbChannelUserExample.Criteria criteria =
                tbChannelUserExample.createCriteria().andUidEqualTo(uid);
        List<TbChannelUser> tbChannelUserList =
                tbChannelUserMapper.selectByExample(tbChannelUserExample);
        if(null == tbChannelUserList || tbChannelUserList.size() != 1) {
            logger.warn("拉新条件：不是新用户---FAIL，" + uid);
            return null;
        }
        TbChannelUser tbChannelUser = tbChannelUserList.get(0);
        if(null == tbChannelUser || tbChannelUser.getUid() <= 0) {
            logger.warn("拉新条件：不存在的用户---FAIL，" + JSONObject.toJSONString(tbChannelUser));
            return null;
        }
        //创建活动
        if(null != activityId) {
            Date createTime = tbClub.getCreateTime();
            Map<String, Object> map = getPointBy(ClubConstants.PULL_GAINS_AMOUNT_SETTING);
            List<Integer> points= (List<Integer>) map.get(ClubConstants.RULE_SETTING_PULL_POINT);
            int limitDay = 30;
            if(CollectionUtils.isNotEmpty(points)) {
                limitDay = points.get(0) > 0 ? points.get(0) : limitDay;
            }
            Date limitTime = DateUtils.addNDay(createTime, limitDay);
            if(limitTime.compareTo(activityCreateTime) == -1) {
                logger.warn("拉新条件：活动创建时间不在俱乐部创建时间30天内---FAIL" +
                        "创建时间：" + activityCreateTime + "限制时间：" + limitTime);
                return null;
            }
        }
        if(null == targetStatus) {
            return tbChannelUser;
        }
        if(tbChannelUser.getStatus() != 3 && tbChannelUser.getStatus() + 1 != targetStatus) {
            logger.warn("当前状态无法直达目标状态，当前状态：" + tbChannelUser.getStatus()
                    + "目标状态：" + targetStatus);
            return null;
        }
        return tbChannelUser;
    }

    /**
     *
     * @param signCount
     * @param clubType 新俱乐部10，老俱乐部11
     * @return
     */
    public int getPointEggs(int signCount, int clubType) {
        Map<String,Object> eggPointMaps = getPointBy(clubType);
        List<Integer> gradeList= (List<Integer>) eggPointMaps.get(ClubConstants.RULE_SETTING_PULL_GRADE);//评分
        List<Integer> pointList= (List<Integer>) eggPointMaps.get(ClubConstants.RULE_SETTING_PULL_POINT);//对应积分
        int pointEgg = 0;
        for (int i = 0; i < gradeList.size(); i++) {
            if(signCount >= gradeList.get(gradeList.size() - 1)) {
                pointEgg = pointList.get(pointList.size() - 1);
                break;
            }
            if (signCount < gradeList.get(i)){
                pointEgg = pointList.get(i);
                break;
            }
        }
        return pointEgg;
    }

    public Double getSignFee() {
        Map<String, Object> map = getPointBy(ClubConstants.PULL_COUNT_SETTING);
        Double lowestFee = (Double) map.get(ClubConstants.RULE_SETTING_PULL_RATE);
        Double limitFee = 15.00;
        if(null != limitFee) {
            lowestFee = lowestFee > 0.0 ? lowestFee : lowestFee;
        }
        return lowestFee;
    }

    /**
     * grade, point
     * @param column
     * @return
     */
    public int getSignCountsSetting(String column) {
        Map<String, Object> map = getPointBy(ClubConstants.PULL_COUNT_SETTING);
        List<Integer> setting= (List<Integer>) map.get(column);
        int limit = 5;
        if(CollectionUtils.isNotEmpty(setting)) {
            limit = setting.get(0) > 0 ? setting.get(0) : limit;
        }
        return limit;
    }

    @Override
    public String getEncryptCode(int type, String code) {
        StringBuilder sb = new StringBuilder();
        sb.append("type=");
        sb.append(type);
        sb.append("&");
        sb.append("code=");
        sb.append(code);
        return DES.encrypt(sb.toString());
    }

    /**
     * 获取明文
     * @param cod
     * @return
     */
    @Override
    public Map<String, String> getDecryptCode (String cod){
        Map<String, String> paramMap = new HashMap<>();
        try {
            String code = DES.decrypt(cod);
            String[] str = code.split("&");
            for (int i = 0; i < str.length; i++) {
                String[] msg = str[i].split("=");
                paramMap.put(msg[0], msg[1]);
            }
        } catch (Exception e) {
        }
        return paramMap;
    }

    public APIResponse getEgg(Map<Integer, Long> uidEggMap) {
        //发放鸟蛋
        List<ReqUserAccumulateModify> reqUserAccumulateModifies = new ArrayList<>();
        for (Map.Entry<Integer, Long> entry : uidEggMap.entrySet()) {
            long egg = entry.getValue();
            if(egg == 0L) {
                continue;
            }
            APIResponse<RespUserInfoBase> response =
                    userServiceFacade.queryUserInfo(entry.getKey());
            if(response == null || !response.isRet()){
                return response;
            }
            RespUserInfoBase userInfo = response.getData();
            ReqUserAccumulateModify modify = new ReqUserAccumulateModify();
            modify.setUid(entry.getKey());
            modify.setAccumulate(egg);
            modify.setAssetsType(AssetsType.ASSETS_EGGS.id.byteValue());
            modify.setSystemCode(Constants.CLUB_SYSTEM_CODE);
            modify.setBusinessCode(ClubConstants.CLUB_EGG_PULL_USER_CODE);
            modify.setReceiver(userInfo.getNickName());
            modify.setPayReceive(AssetsPayReceive.SYSTEM.getName());
            modify.setInfo("拉新奖励");
            reqUserAccumulateModifies.add(modify);
        }
        if(CollectionUtils.isEmpty(reqUserAccumulateModifies)) {
            return APIResponse.returnSuccess();
        }
        APIRequest<List<ReqUserAccumulateModify>> apiRequest = new APIRequest<>();
        logger.warn("发放鸟蛋：" + JSONObject.toJSONString(reqUserAccumulateModifies));
        apiRequest.setData(reqUserAccumulateModifies);
        return userAssetsService.batchModifyEgg(apiRequest);
    }

    /**
     * 是否报名有效 1.注册日期在俱乐部创建时间之后 2.报名的第一个活动，是当前活动且有效
     * @param uid 报名人员UID
     * @param activityId
     * @return
     */
    public boolean isNewSignUser(int uid, int activityId, Date clubCreateTime) {
        //注册时间在俱乐部创建时间之后
        APIResponse<RespUserInfoBase> respUserInfoBase = null;
        respUserInfoBase = userServiceFacade.queryUserInfo(uid);
        RespUserInfoBase userInfo = null;
        if (respUserInfoBase.isRet()) {
            userInfo = respUserInfoBase.getData();
        }
        if(userInfo == null) {

        }
        Date registerTime = userInfo.getRegTime();
        logger.warn("registerTime" + registerTime);
        if(null != registerTime && registerTime.getTime() - clubCreateTime.getTime() < 0) {
            logger.warn("拉新条件---报名用户注册时间在俱乐部创建时间之后---Fail：注册时间："
                    + registerTime + ",俱乐部创建时间：" + clubCreateTime);
            return false;
        }
        //报名的第一个活动，是当前活动且有效
        TbSignUserExample signUserExample = new TbSignUserExample();
        signUserExample.createCriteria()
                .andOrderUserIdEqualTo(uid);
        Limit.buildLimit(0,1);
        List<TbSignUser> signUserList = tbSignUserMapper.selectByExample(signUserExample);
        if(CollectionUtils.isEmpty(signUserList)) {
            return false;
        }
        TbSignUser tbSignUser = signUserList.get(0);
        if(tbSignUser.getActivityId().intValue() == activityId && tbSignUser.getIsCancel() == 0
                && tbSignUser.getManageType() == 4 && tbSignUser.getStatus() == 1){
            logger.warn("拉新条件---报名成员校验通过----PASS");
            return true;
        }
        return false;
    }

    public Map<String,Object> getPointBy(int id){
        Map<String,Object> paramMap=new HashMap<>();
        TbClubIntegralRule tbClubIntegralRule =
                tbClubIntegralRuleMapper.selectByPrimaryKey(id);//积分规则
        logger.warn("------拉新配置----------->>>>>" +
                JSONObject.toJSONString(tbClubIntegralRule));
        String[] strGrade = tbClubIntegralRule.getFinishGrade().split("-");//评分
        List<Integer> gradeList = new ArrayList<>();
        for (int i = 0; i < strGrade.length; i++) {
            gradeList.add(Integer.valueOf(strGrade[i]));
        }
        paramMap.put(ClubConstants.RULE_SETTING_PULL_GRADE, gradeList);
        String[] strPoint = tbClubIntegralRule.getPoint().split("-");//对应的积分
        List<Integer> pointList = new ArrayList<>();
        for (int i = 0; i < strPoint.length; i++) {
            pointList.add(Integer.valueOf(strPoint[i]));
        }
        paramMap.put(ClubConstants.RULE_SETTING_PULL_POINT, pointList);
        paramMap.put(ClubConstants.RULE_SETTING_PULL_RATE, tbClubIntegralRule.getRate());
        return paramMap;
    }

    private TbChannel getTbChannelByCode(String code, int type) {
        TbChannelExample tbChannelExample = new TbChannelExample();
        if(type == 0) {
            //渠道
            tbChannelExample.createCriteria().andExCodeEqualTo(code);
        } else if(type == 1) {
            //分销
            tbChannelExample.createCriteria().andSellCodeEqualTo(code);
        }

        List<TbChannel> channelList = tbChannelMapper.selectByExample(tbChannelExample);
        if(null == channelList || channelList.size() != 1) {
            return null;
        }
        TbChannel tbChannel = channelList.get(0);
        if(null == tbChannel) {
            return null;
        }
        return tbChannel;
    }

    private TbChannelSell getTbChannelSellByCode(String code) {
        TbChannelSellExample tbChannelSellExample = new TbChannelSellExample();
        tbChannelSellExample.createCriteria().andCodeEqualTo(code);
        List<TbChannelSell> channelSellList =
                tbChannelSellMapper.selectByExample(tbChannelSellExample);
        if(null == channelSellList || channelSellList.size() != 1) {
            return null;
        }
        TbChannelSell tbChannelSell = channelSellList.get(0);
        if(null == tbChannelSell) {
            return null;
        }
        return tbChannelSell;
    }

    private void channelIncome(TbChannelUser tbChannelUser, int money) {
        Integer roleId = getRoleIdByCode(tbChannelUser.getType(),null, tbChannelUser.getCode());
        BigDecimal totalMoney = new BigDecimal(money);
        //当前渠道/经销商的信息
        String serialNo = CommonUtils.generateBusinessOrderNo(Constants.CLUB_SYSTEM,
                tbChannelUser.getUid());
        ChannelSellDo model = getChannelSellModel(roleId, tbChannelUser.getType());
        if(null == model) {
            logger.warn("找不到对应的渠道/经销商");
            return;
        }
        if(tbChannelUser.getType() == 0) {
            //渠道商
            insertChannelStream(null, serialNo, tbChannelUser.getUid(), totalMoney,
                    tbChannelUser.getClubId(), model, Constants.BYTE_ZERO,
                    Constants.BYTE_ONE, null);
        } else if(tbChannelUser.getType() == 1) {
            TbChannel tbChannel = tbChannelMapper.selectByPrimaryKey(model.getChId());
            if(null == tbChannel) {
                return;
            }
            ChannelSellDo channelModel = getChannelSellModel(tbChannel.getId(),Constants.BYTE_ZERO);
            BigDecimal sellMoney = new BigDecimal(money*model.getSellRate());
            BigDecimal channelMoney = totalMoney.subtract(sellMoney);
            insertChannelStream(null, serialNo, tbChannelUser.getUid(), sellMoney,
                    tbChannelUser.getClubId(), model, Constants.BYTE_ZERO,
                    Constants.BYTE_ONE, null);
            //渠道
            String channelSerialNo = CommonUtils.generateBusinessOrderNo(Constants.CLUB_SYSTEM,
                    tbChannel.getId());
            insertChannelStream(null, channelSerialNo, tbChannelUser.getUid(), channelMoney,
                    tbChannelUser.getClubId(), channelModel, Constants.BYTE_ZERO,
                    Constants.BYTE_ONE, null);
        }
    }

    public TbChannelStream insertChannelStream(Integer withdrawNo, String serialNo, int uid,
                                               BigDecimal money, int clubId, ChannelSellDo model,
                                               byte type, byte status, String reason) {
        int roleId = model.getId();
        byte roleType = model.getRoleType().byteValue();
        BigDecimal usableMoney = model.getUsableMoney();
        BigDecimal freezeMoney = model.getFreezeMoney();
        TbChannelStream tbChannelStream = new TbChannelStream();
        tbChannelStream.setSerialNo(serialNo);
        tbChannelStream.setStatus(status);
        if(type == Constants.BYTE_ZERO) {
            tbChannelStream.setChUserId(uid);
            tbChannelStream.setClubId(clubId);
            tbChannelStream.setIncome(money);
            usableMoney = usableMoney.add(money);
        } else {
            tbChannelStream.setOutput(money);
            //提现成功
            if(status == Constants.BYTE_ONE) {
                freezeMoney = freezeMoney.subtract(freezeMoney);
            } else if (status == (byte) 3) {
                usableMoney = usableMoney.add(money);
                freezeMoney = freezeMoney.subtract(money);
            }
        }
        tbChannelStream.setRoleType(roleType);
        tbChannelStream.setRoleId(roleId);
        tbChannelStream.setPayChannel(model.getAccountType());
        tbChannelStream.setWithdrawAccount(model.getAccount());
        tbChannelStream.setType(type);
        TbChannelStreamExample tbChannelStreamExample = new TbChannelStreamExample();
        tbChannelStreamExample.createCriteria().andRoleIdEqualTo(roleId)
                .andRoleTypeEqualTo(roleType);
        tbChannelStreamExample.setOrderByClause("id desc");
        tbChannelStreamExample.setLimit(Limit.buildLimit(0,1));
        List<TbChannelStream> tbChannelStreams =
                tbChannelStreamMapper.selectByExample(tbChannelStreamExample);
        if(CollectionUtils.isEmpty(tbChannelStreams)) {
            tbChannelStream.setPreAmount(BigDecimal.ZERO);
        } else {
            tbChannelStream.setPreAmount(tbChannelStreams.get(0).getSufAmount());
        }
        BigDecimal sufAmount = BigDecimal.ZERO;
        if(type == Constants.BYTE_ZERO) {
            sufAmount = tbChannelStream.getPreAmount().add(money);
        } else if(type == Constants.BYTE_ONE) {
            if(status == (byte)3) {
                sufAmount = tbChannelStream.getPreAmount();
            } else if(status == Constants.BYTE_ONE){
                sufAmount = tbChannelStream.getPreAmount().subtract(money);
            }
        } else {
            sufAmount = tbChannelStream.getPreAmount();
        }
        tbChannelStream.setSufAmount(sufAmount);
        tbChannelStream.setWithdrawNo(withdrawNo);
        tbChannelStream.setRemark(reason);
        int count = tbChannelStreamMapper.insertSelective(tbChannelStream);
        if(count <= 0) {
            logger.warn("插入渠道流水失败！" + JSONObject.toJSONString(tbChannelStream));
            return null;
        }

        if(roleType == Constants.BYTE_ZERO) {
            TbChannel updateChannel = new TbChannel();
            updateChannel.setId(roleId);
            updateChannel.setUsableMoney(usableMoney);
            updateChannel.setFreezeMoney(freezeMoney);
            tbChannelMapper.updateByPrimaryKeySelective(updateChannel);
        } else if(roleType == Constants.BYTE_ONE) {
            TbChannelSell updateChannelSell = new TbChannelSell();
            updateChannelSell.setId(roleId);
            updateChannelSell.setUsableMoney(usableMoney);
            updateChannelSell.setFreezeMoney(freezeMoney);
            tbChannelSellMapper.updateByPrimaryKeySelective(updateChannelSell);
        }
        return tbChannelStream;
    }

    public void insertPullClubEgg(int uid, int clubId, int activityId , BigDecimal price,
                                  int counts, int egg, int type) {
        TbChannelClubEgg tbChannelClubEgg = new TbChannelClubEgg();
        tbChannelClubEgg.setUid(uid);
        tbChannelClubEgg.setActivityId(activityId);
        tbChannelClubEgg.setActivityPrice(price);
        tbChannelClubEgg.setSignCounts(counts);
        tbChannelClubEgg.setClubId(clubId);
        tbChannelClubEgg.setEgg(egg);
        tbChannelClubEgg.setType(type);
        tbChannelClubEggMapper.insertSelective(tbChannelClubEgg);
    }

    public ChannelSellDo getChannelSellModel(int roleId, int roleType) {
        ChannelSellDo channelSellDo = new ChannelSellDo();
        channelSellDo.setRoleType(roleType);
        if (roleType == 1) {
            TbChannelSell tbChannelSell =
                    tbChannelSellMapper.selectByPrimaryKey(roleId);
            if (null == tbChannelSell) {
                return null;
            }
            BeanCopierUtils.copyProperties(tbChannelSell, channelSellDo);
            channelSellDo.setMobile(tbChannelSell.getSellMobile());
            channelSellDo.setName(tbChannelSell.getSellName());
            channelSellDo.setRoleType(roleType);

        } else if (roleType == 0) {
            TbChannel tbChannel = tbChannelMapper.selectByPrimaryKey(roleId);
            if (null == tbChannel) {
                return null;
            }
            BeanCopierUtils.copyProperties(tbChannel, channelSellDo);
            channelSellDo.setMobile(tbChannel.getChMobile());
            channelSellDo.setName(tbChannel.getChName());
            channelSellDo.setCode(tbChannel.getExCode());
        }
        return channelSellDo;
    }

    public Integer getRoleIdByCode(int roleType, String code, String exCode) {
        if (roleType == 1) {
            if(null == code) {
                code = exCode;
            }
            TbChannelSellExample tbChannelSellExample = new TbChannelSellExample();
            tbChannelSellExample.createCriteria().andCodeEqualTo(code)
                    .andIsDeleteEqualTo(Constants.BYTE_ZERO);
            List<TbChannelSell> tbChannelSells =
                    tbChannelSellMapper.selectByExample(tbChannelSellExample);
            if (null == tbChannelSells || tbChannelSells.size() != 1) {
                return null;
            }
            TbChannelSell tbChannelSell = tbChannelSells.get(0);
            return tbChannelSell.getId();
        } else if (roleType == 0) {
            TbChannelExample tbChannelExample = new TbChannelExample();
            TbChannelExample.Criteria criteria = tbChannelExample.createCriteria();
            criteria.andIsDeleteEqualTo(Constants.BYTE_ZERO);
            if(null != code) {
                criteria.andSellCodeEqualTo(code);
            } else if(null != exCode){
                criteria.andExCodeEqualTo(exCode);
            }
            List<TbChannel> tbChannels = tbChannelMapper.selectByExample(tbChannelExample);
            if (null == tbChannels || tbChannels.size() != 1) {
                return null;
            }
            TbChannel tbChannel = tbChannels.get(0);
            return tbChannel.getId();
        }
        return null;
    }
}
